package cn.itcast.order.service;

import cn.itcast.feign.clients.UserClient;
import cn.itcast.feign.pojo.User;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderTCCService tccService;

    public Order queryOrderById(int orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.用Feign远程调用
        User user = userClient.findById(order.getUserId());
        // 3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }

    @Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById1(int orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.利用RestTemplate发起http请求，查询用户
        // 2.1.url路径 使用负载均衡，需要改成服务名称，因为是基于服务名获取服务列表
        String url = "http://userservice/user/" + order.getUserId();
//        String url = "http://127.0.0.1:8081/user/" + order.getUserId();
        // 2.2.发送http请求，实现远程调用 get请求
        User user = restTemplate.getForObject(url, User.class);
        // 3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }

    @GlobalTransactional
    public Order TestSeataQueryOrderById(int orderId) {
        // 1.减掉库存，模拟减掉60库存
        int num = 60;
        int flag = orderMapper.updateNumById(orderId,num);
        Order order = orderMapper.findById(orderId);
        // 2.用Feign远程调用
        User user = userClient.findById(order.getUserId());
        // 3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }


    public Order TestTCCQueryOrderById(int orderId) {
        // 1.减掉库存，模拟减掉60库存
        int num = 60;
        int flag = orderMapper.updateNumById(orderId,num);
        Order order = orderMapper.findById(orderId);
        // 2.用Feign远程调用
        User user = userClient.findById(order.getUserId());
        // 3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }

    @GlobalTransactional(
            name = "createOrder",   // 全局事务名称
            rollbackFor = Exception.class  // 触发回滚的异常类型
    )
    public void testSeataTCC(int orderId, int num) {
        tccService.TestTry(orderId,num);
    }
}
